#include "application.h"
#include "widgets/mainwindow.h"
#include "document.h"
#include "modes/editormodemanager.h"
#include "globaldata.h"
#include "undomanager.h"

Application::Application(int &argc, char **argv) :
    QApplication(argc, argv)
{
}

Application &Application::instance()
{
    return *qobject_cast<Application*>(QCoreApplication::instance());
}

QPointer<Document> Application::document() const
{
    return m_document;
}

bool Application::initInstance()
{
	m_globalData = new GlobalData(this);
	m_undoManager = new UndoManager(this);
    m_mainWindow = new MainWindow;
    connect(this, &Application::documentChanged,
            m_mainWindow, &MainWindow::onDocumentChanged);

	initModeManager();
    m_mainWindow->show();

    // update gui according to null document
    emit documentChanged(QPointer<Document>());

    return true;
}

void Application::exitInstance()
{

}

void Application::initModeManager()
{
	m_modeManager = new Modes::EditorModeManager(*m_mainWindow, this);
	connect(this, &Application::documentChanged, 
		m_modeManager, &Modes::EditorModeManager::onDocumentChanged);
}


QPointer<Document> Application::createDocument()
{
    Q_ASSERT(!m_document);
    m_document = new Document(this);
    emit documentChanged(m_document);
    return m_document;
}

void Application::closeDocument()
{
    Q_ASSERT(m_document);
    delete m_document;
    emit documentChanged(m_document);
}

QPointer<GlobalData> Application::globalData() const
{
	return m_globalData;
}

QPointer<Modes::EditorModeManager> Application::modeManager() const
{
	return m_modeManager;
}

QPointer<UndoManager> Application::undoManager() const
{
	return m_undoManager;
}
